// 新增门店页面混入
import {
	getMockInsertStoreList,
	getMockInsertStoreStats,
	getMockProvinceList,
	getMockInsertStoreDetail,
	exportInsertStore
} from '../api/insertStore'

export default {
	data() {
		return {
			// 页面状态
			loading: false,
			refreshing: false,
			loadingMore: false,
			hasMore: true,
			
			// 筛选条件
			selectedProvince: '重庆',
			selectedMonth: '',
			searchKeyword: '',
			showSearch: false,
			showProvinceSelector: false,
			
			// 省份数据
			provinceList: [],
			
			// 分页参数
			currentPage: 1,
			pageSize: 20,
			
			// 数据列表
			dataList: [],
			filteredList: [],
			displayList: [],
			
			// 统计数据
			statsData: {
				monthlyNewStores: 0,
				totalNewStores: 0,
				newStoreRate: 0
			},
			
			// 详情弹窗
			showDetailPopup: false,
			selectedItem: null,
			
			// 内容高度
			contentHeight: 400
		}
	},
	
	computed: {
		// 格式化当前月份
		currentMonthText() {
			const now = new Date()
			return `${now.getFullYear()}年${now.getMonth() + 1}月`
		},
		
		// 总门店数
		totalStores() {
			return this.displayList.length
		},
		
		// 新增门店数
		newStoresCount() {
			return this.displayList.filter(item => item.storeType === '新增').length
		},
		
		// 续约门店数
		renewalStoresCount() {
			return this.displayList.filter(item => item.storeType === '续约').length
		},
		
		// 升级门店数
		upgradeStoresCount() {
			return this.displayList.filter(item => item.storeType === '升级').length
		}
	},
	
	onLoad() {
		this.initPage()
	},
	
	onReady() {
		this.calculateContentHeight()
	},
	
	onPullDownRefresh() {
		this.onRefresh()
	},
	
	onReachBottom() {
		this.loadMore()
	},
	
	methods: {
		// 初始化页面
		async initPage() {
			this.loading = true
			try {
				// 设置默认月份
				this.setDefaultMonth()
				
				// 并行加载数据
				await Promise.all([
					this.loadProvinceList(),
					this.loadInsertStoreData(),
					this.loadStatsData()
				])
			} catch (error) {
				console.error('初始化页面失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 设置默认月份
		setDefaultMonth() {
			const now = new Date()
			this.selectedMonth = now.getMonth() + 1
		},
		
		// 加载省份列表
		async loadProvinceList() {
			try {
				const res = await getMockProvinceList()
				if (res.code === 200) {
					this.provinceList = res.data
				}
			} catch (error) {
				console.error('加载省份列表失败:', error)
			}
		},
		
		// 加载新增门店数据
		async loadInsertStoreData(isLoadMore = false) {
			try {
				const params = {
					page: isLoadMore ? this.currentPage + 1 : 1,
					pageSize: this.pageSize,
					province: this.selectedProvince,
					month: this.selectedMonth,
					keyword: this.searchKeyword
				}
				
				const res = await getMockInsertStoreList(params)
				
				if (res.code === 200) {
					const newData = res.data.list || []
					
					if (isLoadMore) {
						this.dataList = [...this.dataList, ...newData]
						this.currentPage += 1
					} else {
						this.dataList = newData
						this.currentPage = 1
					}
					
					// 检查是否还有更多数据
					this.hasMore = newData.length === this.pageSize
					
					// 应用筛选
					this.applyFilters()
				}
			} catch (error) {
				console.error('加载新增门店数据失败:', error)
				throw error
			}
		},
		
		// 加载统计数据
		async loadStatsData() {
			try {
				const params = {
					province: this.selectedProvince,
					month: this.selectedMonth
				}
				
				const res = await getMockInsertStoreStats(params)
				
				if (res.code === 200) {
					this.statsData = res.data
				}
			} catch (error) {
				console.error('加载统计数据失败:', error)
				// 统计数据加载失败不影响主要功能
			}
		},
		
		// 应用筛选
		applyFilters() {
			let filtered = [...this.dataList]
			
			// 搜索筛选
			if (this.searchKeyword) {
				const keyword = this.searchKeyword.toLowerCase()
				filtered = filtered.filter(item => 
					item.storeName.toLowerCase().includes(keyword) ||
					item.region.toLowerCase().includes(keyword) ||
					item.area.toLowerCase().includes(keyword) ||
					item.storeType.toLowerCase().includes(keyword)
				)
			}
			
			this.filteredList = filtered
			this.displayList = filtered
		},
		
		// 切换省份
		async switchProvince(province) {
			if (this.selectedProvince === province) return
			
			this.selectedProvince = province
			this.showProvinceSelector = false
			
			this.loading = true
			try {
				await Promise.all([
					this.loadInsertStoreData(),
					this.loadStatsData()
				])
			} catch (error) {
				console.error('切换省份失败:', error)
				this.showError('加载数据失败')
			} finally {
				this.loading = false
			}
		},
		
		// 显示省份选择器
		showProvincePickerAction() {
			const provinceNames = this.provinceList.map(item => item.name)
			uni.showActionSheet({
				itemList: provinceNames,
				success: (res) => {
					const selectedProvince = this.provinceList[res.tapIndex]
					this.switchProvince(selectedProvince.name)
				}
			})
		},
		
		// 刷新数据
		async onRefresh() {
			this.refreshing = true
			try {
				this.currentPage = 1
				this.hasMore = true
				await Promise.all([
					this.loadInsertStoreData(),
					this.loadStatsData()
				])
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				})
			} catch (error) {
				console.error('刷新数据失败:', error)
				this.showError('刷新失败')
			} finally {
				this.refreshing = false
				uni.stopPullDownRefresh()
			}
		},
		
		// 加载更多
		async loadMore() {
			if (this.loadingMore || !this.hasMore) return
			
			this.loadingMore = true
			try {
				await this.loadInsertStoreData(true)
			} catch (error) {
				console.error('加载更多失败:', error)
				this.showError('加载失败')
			} finally {
				this.loadingMore = false
			}
		},
		
		// 搜索处理
		handleSearch() {
			// 防抖处理
			clearTimeout(this.searchTimer)
			this.searchTimer = setTimeout(() => {
				this.applyFilters()
			}, 300)
		},
		
		// 清除搜索
		clearSearch() {
			this.searchKeyword = ''
			this.applyFilters()
		},
		
		// 切换搜索显示
		toggleSearch() {
			this.showSearch = !this.showSearch
			if (!this.showSearch) {
				this.clearSearch()
			}
		},
		
		// 行点击事件
		async handleRowClick(item) {
			try {
				uni.showLoading({
					title: '加载中...'
				})
				
				const res = await getMockInsertStoreDetail(item.id)
				
				if (res.code === 200) {
					this.selectedItem = {
						...item,
						...res.data
					}
					this.showDetailPopup = true
				}
			} catch (error) {
				console.error('获取详情失败:', error)
				this.showError('获取详情失败')
			} finally {
				uni.hideLoading()
			}
		},
		
		// 计算内容高度
		calculateContentHeight() {
			const systemInfo = uni.getSystemInfoSync()
			const windowHeight = systemInfo.windowHeight
			// 减去导航栏、筛选区域、统计区域、明细标题等高度
			this.contentHeight = windowHeight - 350
		},
		
		// 格式化数字
		formatNumber(num) {
			if (num === null || num === undefined) return '0'
			
			const number = parseFloat(num)
			if (isNaN(number)) return '0'
			
			return number.toLocaleString('zh-CN')
		},
		
		// 显示错误信息
		showError(message) {
			uni.showToast({
				title: message,
				icon: 'none',
				duration: 2000
			})
		},
		
		// 导出数据
		async handleExport() {
			try {
				uni.showLoading({
					title: '导出中...'
				})
				
				const params = {
					province: this.selectedProvince,
					month: this.selectedMonth,
					keyword: this.searchKeyword,
					exportType: 'excel'
				}
				
				// 模拟导出过程
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '导出成功',
						icon: 'success'
					})
				}, 2000)
				
			} catch (error) {
				uni.hideLoading()
				console.error('导出失败:', error)
				this.showError('导出失败')
			}
		}
	},
	
	// 页面卸载时清除定时器
	beforeDestroy() {
		if (this.searchTimer) {
			clearTimeout(this.searchTimer)
		}
	}
}
